#include "login.h"
#include "ui_login.h"
#include <QDebug>

Login::Login(QList<User *> users, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Login)
{
    ui->setupUi(this);
    this->users = users;

    this->initScene(); //初始化窗口
}

Login::~Login()
{
    delete ui;
}

//显示当前界面
void Login::showLogin(){
    //清空文本框中的内容
    ui->name->clear();
    ui->pwd->clear();

    this->show(); //显示当前界面
    //QSound::play(GAME_BGM_GAME_MENU);
}

void Login::on_login_clicked()
{
    //获取文本框值
    QString username=ui->name->text();
    QString password=ui->pwd->text();

    //判断输入用户名密码是否正确
    this->getAllUsers();
    int flag=0;
    for(int i=0;i<users.size();i++){
        if(QString::compare(username,users.at(i)->userName)==0
               && QString::compare(password,users.at(i)->passWord)==0){
            flag=1;
            loginuser=users.at(i);
            break;
        }
    }

    //根据标志跳转窗口
    if(flag==0){
            QMessageBox::warning(NULL,GAME_NAME,"用户名或密码错误！",QMessageBox::Ok);
        }else{
            QMessageBox::information(NULL,GAME_NAME,"登录成功！",QMessageBox::Ok);
            emit sendLoginUser(loginuser);

            this->hide();
        }

}

//从文件获取所有的用户
void Login::getAllUsers(){
    this->users.clear(); //清空链表
    //读取文件
    QFile file ("./user.txt");
    file.open(QIODevice::ReadOnly| QIODevice::Text );
    QByteArray t=file.readAll();
    QString alltext=QString(t);
    QStringList list=alltext.split("\n");
    for (int i=0; i<list.size() ;i++ ) {
        QStringList temp=list[i].split(" ");
        if(temp.size()>4){
            this->users.append(new User(temp[0],temp[1], temp[2], temp[3], temp[4]));
        }
    }
    file.close();
    //往user中临时存数据
    //users.append(new User("123123","123123"));
}

void Login::on_back_clicked()
{
    emit this->showMe(); //发送信号显示我界面
    this->hide(); //隐藏当前界面
}

//初始化窗口
void Login::initScene(){
//    setWindowTitle(GAME_NAME); //设置窗口标题
//    setWindowIcon(QIcon(GAME_ICON_)); //设置窗口图标
}
